"""Your Specific Workflow Example: cd /path/to/project1 && make build && sbatch run.slurm"""

import asyncio
from fastmcp import Client
import sys
import os

# Add the src directory to the path for imports
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from server import mcp, initialize_managers


async def your_exact_workflow():
    """Demonstrate your exact workflow: cd /path/to/project1 && make build && sbatch run.slurm"""
    print("=== Your Specific Workflow Example ===")
    
    async with Client(mcp) as client:
        connection_id = "user@hpc-server:22"  # Replace with your actual connection
        
        print("🚀 Method 1: NEW - Using execute_sequential_commands (RECOMMENDED)")
        print("This new tool maintains session state and tracks directory changes!\n")
        
        # Your exact workflow using the new sequential commands tool
        workflow_commands = """
        cd /path/to/project1
        make build  
        sbatch run.slurm
        """
        
        result = await client.call_tool("execute_sequential_commands", {
            "connection_id": connection_id,
            "commands": workflow_commands,
            "working_dir": "~",
            "stop_on_error": True
        })
        print("Sequential commands result:")
        print(result.text)
        print("\n" + "="*60 + "\n")
        
        print("🔧 Method 2: Traditional chained command")
        
        # Traditional single command with && chains
        chained_result = await client.call_tool("execute_command", {
            "connection_id": connection_id,
            "command": "cd /path/to/project1 && make build && sbatch run.slurm",
            "working_dir": "~"
        })
        print("Chained command result:")
        print(chained_result.text)
        print("\n" + "="*60 + "\n")
        
        print("🔧 Method 3: Step-by-step with working_dir parameter")
        
        # Step-by-step execution with working directory
        steps = [
            ("make build", "/path/to/project1"),
            ("sbatch run.slurm", "/path/to/project1")
        ]
        
        for step_num, (command, work_dir) in enumerate(steps, 1):
            print(f"Step {step_num}: {command} (in {work_dir})")
            step_result = await client.call_tool("execute_command", {
                "connection_id": connection_id,
                "command": command,
                "working_dir": work_dir
            })
            print(f"Result: {step_result.text[:200]}...")
            print()


async def advanced_workflow_examples():
    """Advanced workflows showing more complex sequential operations"""
    print("=== Advanced Sequential Workflow Examples ===")
    
    async with Client(mcp) as client:
        connection_id = "user@hpc-server:22"
        
        print("📋 Example 1: Complex build and test workflow")
        
        complex_workflow = """
        # Navigate to project
        cd /home/user/projects/simulation
        
        # Clean previous builds
        make clean
        
        # Load required modules
        module load gcc/11.2
        module load openmpi/4.1
        
        # Build with optimizations
        make build CFLAGS="-O3 -fopenmp"
        
        # Run quick test
        ./simulation --test --verbose
        
        # If test passes, submit production job
        sbatch --time=02:00:00 --nodes=4 production.slurm
        """
        
        result1 = await client.call_tool("execute_sequential_commands", {
            "connection_id": connection_id,
            "commands": complex_workflow,
            "working_dir": "~",
            "stop_on_error": True
        })
        print("Complex workflow result:")
        print(result1.text[:500] + "..." if len(result1.text) > 500 else result1.text)
        print("\n" + "="*60 + "\n")
        
        print("📋 Example 2: Multi-project dependency workflow")
        
        dependency_workflow = """
        # Build library first
        cd /home/user/projects/math_lib
        make clean && make install
        
        # Build main application
        cd /home/user/projects/main_app
        make clean
        make build
        
        # Create job script on the fly
        echo '#!/bin/bash
#SBATCH --job-name=main_simulation
#SBATCH --partition=compute
#SBATCH --nodes=2
#SBATCH --time=01:00:00
cd /home/user/projects/main_app
./main_simulation --input=data.txt' > dynamic_job.slurm
        
        # Submit the dynamically created job
        sbatch dynamic_job.slurm
        """
        
        result2 = await client.call_tool("execute_sequential_commands", {
            "connection_id": connection_id,
            "commands": dependency_workflow,
            "working_dir": "~",
            "stop_on_error": False  # Continue even if some steps fail
        })
        print("Dependency workflow result:")
        print(result2.text[:500] + "..." if len(result2.text) > 500 else result2.text)


async def interactive_development_simulation():
    """Simulate an interactive development session"""
    print("\n=== Interactive Development Session Simulation ===")
    
    async with Client(mcp) as client:
        connection_id = "user@hpc-server:22"
        
        print("👨‍💻 Simulating typical HPC development workflow...")
        
        # Simulate a typical development session
        dev_session = """
        # Setup development environment
        cd /home/user/workspace
        mkdir -p experiment_2024_07_21
        cd experiment_2024_07_21
        
        # Initialize git repository
        git init
        
        # Create initial source file (simulation)
        echo '#include <stdio.h>
#include <omp.h>
int main() {
    #pragma omp parallel
    {
        printf("Hello from thread %d\\n", omp_get_thread_num());
    }
    return 0;
}' > hello_omp.c
        
        # Compile and test
        gcc -fopenmp hello_omp.c -o hello_omp
        ./hello_omp
        
        # Create Slurm job script
        echo '#!/bin/bash
#SBATCH --job-name=hello_test
#SBATCH --partition=debug
#SBATCH --nodes=1
#SBATCH --cpus-per-task=4
#SBATCH --time=00:05:00
cd $PWD
export OMP_NUM_THREADS=4
./hello_omp' > test_job.slurm
        
        # Submit test job
        sbatch test_job.slurm
        """
        
        result = await client.call_tool("execute_sequential_commands", {
            "connection_id": connection_id,
            "commands": dev_session,
            "working_dir": "~",
            "stop_on_error": True
        })
        
        print("Development session result:")
        print(result.text)


async def main():
    """Run all workflow examples"""
    print("SSH Slurm MCP Server - Your Specific Workflow Examples")
    print("Demonstrates: cd /path/to/project1 && make build && sbatch run.slurm\n")
    
    # Initialize managers
    initialize_managers()
    
    await your_exact_workflow()
    await advanced_workflow_examples()
    await interactive_development_simulation()
    
    print("\n🎉 All workflow examples completed!")
    print("\n💡 Key Benefits of execute_sequential_commands:")
    print("  ✅ Maintains working directory state across commands")
    print("  ✅ Provides detailed per-command output and error tracking")
    print("  ✅ Supports error handling with stop_on_error option")
    print("  ✅ Handles directory changes (cd commands) intelligently")
    print("  ✅ Perfect for complex multi-step HPC workflows")


if __name__ == "__main__":
    asyncio.run(main())
